﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WkHtmlToXSharp;
using System.Threading;

namespace NCP.Recruiting.Web.Framework
{
    public static class HtmlConvertPdf
    {
       
        public static void DownloadPdf(this HttpContext context, string url, string filename)
        {
            Func<object, byte[]> fun = (str) => Process(url);
            var task = Task.Factory.StartNew(fun, null, TaskCreationOptions.None);

            Task.WaitAll(task);
            var bufferPDF = task.Result;
            context.Response.Buffer = true;
            context.Response.Clear();
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", "inline; filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
            context.Response.BinaryWrite(bufferPDF);
            context.Response.Flush();
            context.Response.End();
        }

         [STAThread]
        private static byte[] Process(string url)
        {
            WkHtmlToPdfConverter wol = new WkHtmlToPdfConverter();
            var bufferPDF = wol.GetUrlPDF(url);
            return bufferPDF;
        }
    }
}
